package st.business.tepth.business.history;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;

import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.business.bean.HistoryConditionBean;
import st.business.tepth.business.bean.HistoryResultBean;
import st.business.tepth.business.history.detail.HistoryDetailDelegate;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.recycler.BaseDecoration;
import st.shadow.library.ui.recycler.MultipleItemEntity;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-03-02 15:39
 */

public class HistoryDelegate extends MvpFragment<HistoryPresenter> implements HistoryContract.View {
    private static final int PAGE_SIZE = 20;

    public static HistoryDelegate newInstance() {
        return new HistoryDelegate();
    }

    @BindView(R2.id.recycler_view_key)
    RecyclerView mRecyclerViewKey;
    @BindView(R2.id.recycler_view_search_result)
    RecyclerView mRecyclerViewResult;
    @BindView(R2.id.tv_tile)
    TextView mTvTitle;
    @BindView(R2.id.et_date_start)
    TextView mTvDateStart;
    @BindView(R2.id.et_date_end)
    TextView mTvDateEnd;
    @BindView(R2.id.et_search)
    EditText mEtSearch;
    private HistorySearchKeyAdapter mKeyAdapter;
    private HistoryResultAdapter mHistoryResultAdapter;
    private int mCurrentPage = 1;
    private DialogLoader mDialogLoader;

    @Override
    public HistoryPresenter getPresenter() {
        return new HistoryPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_history;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mTvTitle.setText("历史查询");
        mRecyclerViewKey.setLayoutManager(new GridLayoutManager(_mActivity, 6));
        mKeyAdapter = new HistorySearchKeyAdapter(null);
        mKeyAdapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
            @Override
            public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                MultipleItemEntity entity = mKeyAdapter.getItem(position);
                if (entity != null) {
                    if (entity.getItemType() == HistorySearchKeyAdapter.TYPE_0) {
                        return 6;
                    } else {
                        return 1;
                    }
                } else {
                    return 6;
                }
            }
        });
        mRecyclerViewKey.setAdapter(mKeyAdapter);

        mRecyclerViewResult.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerViewResult.addItemDecoration(BaseDecoration.
                create(Color.parseColor("#f0f0f0"), 1));
        mRecyclerViewResult.setAdapter(mHistoryResultAdapter =
                new HistoryResultAdapter(R.layout.item_history_result, null));
        mHistoryResultAdapter.setEmptyView(R.layout.view_search_empty,
                (ViewGroup) mRecyclerViewResult.getParent());
        mHistoryResultAdapter.setOnLoadMoreListener(
                new BaseQuickAdapter.RequestLoadMoreListener() {
                    @Override
                    public void onLoadMoreRequested() {
                        loadMore();
                    }
                }, mRecyclerViewResult);
        mRecyclerViewResult.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter,
                                               View view, int position) {
                HistoryResultBean resultBean = (HistoryResultBean) adapter.getItem(position);
                if (resultBean != null) {
                    List<HistoryResultBean.RepairsBean> repairsBeans = resultBean.getRepairs();
                    if (view.getId() == R.id.tv_report_content_detail) {
                        if (repairsBeans != null && !repairsBeans.isEmpty()) {
                            DialogHistoryReportDetail dialogHistoryReportDetail =
                                    new DialogHistoryReportDetail(_mActivity, repairsBeans);
                            dialogHistoryReportDetail.setCanceledOnTouchOutside(false);
                            Window dialogWindow = dialogHistoryReportDetail.getWindow();
                            if (dialogWindow != null) {
                                WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                                lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
                                lp.height = ScreenUtils.getScreenHeight() * 520 / 1024; // 高度
                                dialogWindow.setGravity(Gravity.CENTER);
                                dialogWindow.setAttributes(lp);
                                dialogHistoryReportDetail.show();
                            }
                        }
                    } else if (view.getId() == R.id.tv_operation) {
                        start(HistoryDetailDelegate.newInstance(resultBean.getId()));
                    }
                }
            }
        });
        mPresenter.getCondition(UserManager.getInstance().getToken());
        mDialogLoader = new DialogLoader(_mActivity);
    }

    @OnClick({R2.id.tv_back})
    public void onBack() {
        pop();
    }

    @OnClick(R2.id.et_date_start)
    public void onChooseDateStart() {
        final Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(_mActivity,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String date = year + "-" + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) +
                                "-" + (dayOfMonth < 10 ? ("0" + dayOfMonth) : dayOfMonth);
                        mTvDateStart.setText(date);
                        mTvDateStart.setTextColor(Color.parseColor("#333333"));
                    }
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    @OnClick(R2.id.et_date_end)
    public void onChooseDateEnd() {
        final Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(_mActivity,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String date = year + "-" + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) +
                                "-" + (dayOfMonth < 10 ? ("0" + dayOfMonth) : dayOfMonth);
                        mTvDateEnd.setText(date);
                        mTvDateEnd.setTextColor(Color.parseColor("#333333"));
                    }
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    @Override
    public void showCondition(HistoryConditionBean conditionBean) {
        if (mKeyAdapter != null) {
            mKeyAdapter.setNewData(new HistoryDataConvert()
                    .convertToConditions(conditionBean));
        }
    }

    @Override
    public void showError(String msg) {
        mDialogLoader.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void showHistoryResult(boolean isRefresh, List<HistoryResultBean> list) {
        mHistoryResultAdapter.setEmptyView(R.layout.view_search_empty,
                (ViewGroup) mRecyclerViewResult.getParent());
        if (mHistoryResultAdapter != null) {
            mCurrentPage++;
            final int size = list == null ? 0 : list.size();
            if (isRefresh) {
                mHistoryResultAdapter.setNewData(list);
            } else {
                if (size > 0) {
                    mHistoryResultAdapter.addData(list);
                }
            }
            if (size < PAGE_SIZE) {
                //第一页如果不够一页就不显示没有更多数据布局
                mHistoryResultAdapter.loadMoreEnd(isRefresh);
            } else {
                mHistoryResultAdapter.loadMoreComplete();
            }
        }
    }

    @OnClick(R2.id.tv_search)
    public void onSearch() {
        if (mHistoryResultAdapter != null) {
            mHistoryResultAdapter.setNewData(null);
            mHistoryResultAdapter.setEmptyView(R.layout.view_loading,
                    (ViewGroup) mRecyclerViewResult.getParent());
        }
        mCurrentPage = 1;
        requestData(true);

    }

    private void loadMore() {
        requestData(false);
    }

    private void requestData(final boolean isRefresh) {
        String classificationIds = "";
        String typeIds = "";
        if (mKeyAdapter != null) {
            String[] ids = mKeyAdapter.getSelectKeys();
            classificationIds = ids[0] == null ? "" : ids[0];
            typeIds = ids[1] == null ? "" : ids[1];
        }
        String startDate = mTvDateStart.getText().toString();
        String endDate = mTvDateEnd.getText().toString();
        if ("请选择开始日期".equals(startDate)) {
            startDate = "";
        }
        if ("请选择结束日期".equals(endDate)) {
            endDate = "";
        }
        mPresenter.getHistoryData(isRefresh, UserManager.getInstance().getToken(),
                mEtSearch.getText().toString(), startDate,
                endDate, classificationIds, typeIds, PAGE_SIZE,
                mCurrentPage);
    }

}